#!/usr/bin/env python
#  -*- coding: utf-8 -*- 
__author__ = 'liu'

"""
更新和获取期货合约交易所标准保证金比率
修改记录:
1. 2023.7.1 创建
2. 2023.7.7 改每次遍历一个品种保存为整体保存
3. 2024.8.8 去掉Json目录，直接放根目录
4. 2024.9.15 使用公共库v13
5. 2024.9.18 更换数据源网址
6. 2024.10.2 修改保存保证金数据接口
7. 2024.11.2 使用公共库v15
8. 2025.3.10 使用公共库v16
9. 2025.6.26 修改可切换数据源
"""
import pandas as pd
from common_lib_v16 import *

MARGIN_FILE = "std_margin_ratio.json"
MARGIN_URL_1 = "http://hq.9qihuo.com/shouxufei/heyue/all"
MARGIN_URL_2 = "https://www.9qihuo.com/qihuoshouxufei"

# 获取标准保证金比率
def get_std_margin_ratio(future_symbol):
    if '.' in future_symbol:
        key = future_symbol.split('.')[1]
    else:
        key = future_symbol
    ratio = get_variable(MARGIN_FILE, key, -1.0)
    if ratio < 0.0:
        return 0.25  # 取不到保证金比率则使用一个较大的数值
    else:
        return ratio

# 保存标准保证金比率到json文件1
def save_std_margin_ratio_to_json_1():
    dt = {}
    json_file = MARGIN_FILE
    if exists(json_file):
        try:
            with open(json_file, "r") as r:
                dt = load(r)
        except Exception as e:
            print(e)

    tables = pd.read_html(MARGIN_URL_1)
    df = tables[0]
    for index in range(len(df)):
        if (('0' in df[1].iloc[index]) or ('1' in df[1].iloc[index])):
            future_symbol = df[1].iloc[index]
            std_margin_ratio = float(df[5].iloc[index].strip('%')) / 100
            dt[future_symbol] = std_margin_ratio

    try:
        with open(json_file, "w") as w:
            dump(dt, w)
    except Exception as e:
        print(e)

# 保存标准保证金比率到json文件2
def save_std_margin_ratio_to_json_2():
    dt = {}
    json_file = MARGIN_FILE
    if exists(json_file):
        try:
            with open(json_file, "r") as r:
                dt = load(r)
        except Exception as e:
            print(e)

    tables = pd.read_html(MARGIN_URL_2)
    df = tables[0]
    # df = df.rename(columns={0:"合约品种",1:"现价",2:"涨/跌停板",3:"买开保证金",4:"卖开保证金",5:"每手保证金",6:"开仓手续费",7:"平昨手续费",8:"平今手续费",9:"每跳毛利/元",10:"开平手续费",11:"每跳净利润",12:"是否是主力合约"})
    for index in range(len(df)):
        if '(' in df[0].iloc[index]:
            future_symbol = df[0].iloc[index].split('(')[1].strip(')')
            std_margin_ratio = float(df[3].iloc[index].replace('%', '')) / 100
            dt[future_symbol] = std_margin_ratio
    try:
        with open(json_file, "w") as w:
            dump(dt, w)
    except Exception as e:
        print(e)

if __name__ == '__main__':
    save_std_margin_ratio_to_json_1()
